package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.Util.CopyUtil;
import com.jiawa.wiki.Util.SnowFlake;
import com.jiawa.wiki.domain.Ebook;
import com.jiawa.wiki.domain.EbookExample;
import com.jiawa.wiki.mapper.EbookMapper;
import com.jiawa.wiki.req.EbookQueryReq;
import com.jiawa.wiki.req.EbookSaveRep;
import com.jiawa.wiki.resp.EbookQueryResp;
import com.jiawa.wiki.resp.PageResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EbookService {
    @Resource
    public EbookMapper ebookMapper;

    @Resource
    public SnowFlake snowFlake;

    private final static Logger LOG = LoggerFactory.getLogger(EbookService.class);

    public
    PageResp<EbookQueryResp> getlist(EbookQueryReq req) {

        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();

        //
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%"+req.getName()+"%");
        }

        //categoryID
        if (!ObjectUtils.isEmpty(req.getCategory2Id())) {
            criteria.andCategory2IdEqualTo(req.getCategory2Id());
        }


        PageHelper.startPage(req.getPage(),req.getSize());

        //直接从数据库取数据
        List <Ebook> ebookList =ebookMapper.selectByExample(ebookExample);
        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
        LOG.info("总行数：{}",pageInfo.getTotal());
        LOG.info("总行数：{}",pageInfo.getTotal());
        //空列表
        List <EbookQueryResp> list = CopyUtil.copyList(ebookList, EbookQueryResp.class);
        //
        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);

        return pageResp;

        }
        public void save(EbookSaveRep req){
            Ebook ebook=CopyUtil.copy(req,Ebook.class);

            if(!ObjectUtils.isEmpty(req.getId())) {
                //更新
                ebookMapper.updateByPrimaryKey(ebook);
            }else {
                //新增
                snowFlake.nextId();
                ebook.setId(snowFlake.nextId());
                ebookMapper.insert(ebook);
        }}
    public void delete(long id){
        ebookMapper.deleteByPrimaryKey(id);
    }



}
